package com.common.orm;


import com.common.orm.sqlparameters.SqlParameter;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author Dmitry Savchenko
 */
class SqlExecuterWithoutResult extends SqlExecuter {

    public SqlExecuterWithoutResult(Connection connection, String sql, ClassData classData,SqlParameter... values) throws SQLException {
        init(connection, sql, classData,values);
    }

    public int execute() throws SQLException {
        try {
            return preparedStatement.executeUpdate();
        } finally {
            try {
                preparedStatement.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    public int insert(ClassData classData, Object object, boolean autoInsertPrimaryKey, String[] processedFields) throws SQLException {
        try {
            int position = 1;
            if (processedFields != null) {
                for (String field : processedFields) {
                    SqlParameter param = OrmUtils.getSqlParameterFromString(classData, object, field);
                    param.process(position, preparedStatement);
                    position++;
                }
            } else {
                if (autoInsertPrimaryKey) {
                    for (MethodColumnPair mcp : classData.getColumns()) {
                        if (mcp.isPrimaryKey()) {
                            continue;
                        }

                        SqlParameter param = OrmUtils.getSqlParameterFromString(classData, object, mcp.getColumn());
                        param.process(position, preparedStatement);
                        position++;
                    }
                } else {
                    for (MethodColumnPair mcp : classData.getColumns()) {
                        SqlParameter param = OrmUtils.getSqlParameterFromString(classData, object, mcp.getColumn());
                        param.process(position, preparedStatement);
                        position++;
                    }
                }
            }
            preparedStatement.execute();
            if(autoInsertPrimaryKey){
                if(classData.getPrimaryKey()!=null){
                    if(classData.getPrimaryKey().getFieldType()==Integer.class){
                        int last=lastval();
                        try {
                            classData.getPrimaryKey().getSetter().invoke(object, (Integer)last);
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    }
                }
            }
            return 0;
        } finally {
            try {
                preparedStatement.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
    
    private int lastval(){
        return Orm.lastval();
    }
}
